import { createRouter, createWebHashHistory, NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '../library/cookieUtil'
import { useUserStore } from "../store/user";
import { routes } from './base-routes'
import { userInfo } from '../api/module/user/user';
import { useConfigStore } from '../store/config';

const router = createRouter({
  history: createWebHashHistory(),
  routes
})
let load = 0
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  NProgress.configure({ showSpinner: false });
  if (to.meta.title) NProgress.start();
  const token = getToken();
  if (to.path === '/login' && !token) {
    next();
    NProgress.done();
  } else {
    if (!token) {
      next(`/login?redirect=${to.path}&params=${JSON.stringify(to.query ? to.query : to.params)}`);
    } else if (token && to.path === '/login') {
      next('/workspace');
      NProgress.done();
    } else if (load === 0) {
      //刷新后重新远程获取用户及系统配置
      const userStore = useUserStore();
      const configStore = useConfigStore();
      userInfo().then((res) => {
          if (res.status == 1) {
            userStore.userInfo = res.userInfo;
            userStore.statistics = res.statistics;
            userStore.userMenu = res.asMenus;
            userStore.menuBottons = res.asMenuBottons;
            configStore.systemConfig = res.sytemConfig;
            configStore.dicts = res.listViewDictData;
            configStore.parameter = res.configParms;
          }
        })
      load++
      routerData(userStore.userMenu || "");      
      next({ path: to.path, query: to.query })
    } else {
      next()
    }
  }
})

const viteComponents = import.meta.glob("../**/*.vue");
const routerData = (result: any) => {
  if (result) {
    result.forEach((menu: any) => {
      if (menu.children) {
        menu.children.forEach((item: any) => {
          if (!item.comUrl) return
          let route: any = {
            path: item.id,
            name: item.title,
            redirect: item.redirect,
            meta: {
              title: item.title,
            },
            component: viteComponents['../views/' + item.comUrl],
          }
          router.addRoute("home", route)
        })
      }
      // if (menu.children && menu.children.length) {
      //   routerData(menu.children);
      // }
    })
  }
}

router.afterEach(() => {
  NProgress.done();
})

export default router